import sys
import time
import logging
from typing import List
import winerror
import traceback
import win32event
import win32service
import servicemanager
import win32serviceutil

logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s: %(message)s")

services: List[dict] = [
    {
        "routine": None,
        "model": "WorkWS04AIMAGE()"
    }
]


class AppKZLServicesImage(win32serviceutil.ServiceFramework):
    _svc_name_ = "AppKZLServicesImage"
    _svc_display_name_ = "AppKZLServicesImage"
    _svc_description_ = "AppKZLServicesImage"

    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
        self.status: bool = True

    def SvcDoRun(self):
        time.sleep(2.8)
        # noinspection PyBroadException
        try:
            while True:
                for f_index, f_itr in enumerate(services):
                    if f_itr.get("routine") is None or f_itr.get("routine").is_alive() is False:
                        f_itr["routine"] = eval(f_itr.get("model"))
                        f_itr["routine"].start()
                time.sleep(2.8)
        except Exception as e:
            logging.error(msg=traceback.print_exc())

    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)
        self.ReportServiceStatus(win32service.SERVICE_STOPPED)
        self.status = False


if __name__ == '__main__':
    if len(sys.argv) == 1:
        try:
            servicemanager.Initialize()
            servicemanager.PrepareToHostSingle(AppKZLServicesImage)
            servicemanager.StartServiceCtrlDispatcher()
        except Exception as details:
            if details == winerror.ERROR_FAILED_SERVICE_CONTROLLER_CONNECT:
                win32serviceutil.usage()
    else:
        win32serviceutil.HandleCommandLine(AppKZLServicesImage)

    # noinspection PyBroadException
    # try:
    #     while True:
    #         for f_index0, f_itr0 in enumerate(services):
    #             if f_itr0.get("routine") is None or f_itr0.get("routine").is_alive() is False:
    #                 f_itr0["routine"] = eval(f_itr0.get("model"))
    #                 f_itr0["routine"].start()
    #         time.sleep(2.8)
    # except Exception as e:
    #     logging.error(msg=traceback.print_exc())
